import Vue from 'vue'
import VueRouter from 'vue-router'

const Login = ()=>import('../views/Login.vue')
const Layout = ()=>import('../views/Layout.vue')
const Index = ()=>import('../views/Index.vue')
const Menu = ()=>import('../views/menu/Index.vue')
const Role = ()=>import('../views/role/Index.vue')
const User = ()=>import('../views/user/Index.vue')
const Category = ()=>import('../views/category/Index.vue')
const Specs = ()=>import('../views/specs/Index.vue')
const Goods = ()=>import('../views/goods/Index.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login,
    meta: {
      title: '欢迎登录'
    }
  },
  {
    path: '/',
    component: Layout,
    children: [
      {path: '', component: Index},
      {path: 'menu', component: Menu},
      {path: 'role', component: Role},
      {path: 'user', component: User},
      {path: 'category', component: Category},
      {path: 'specs', component: Specs},
      {path: 'goods', component: Goods},
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,  // process进程 env环境  process.env 当前vue代码的运行环境 开发？测试？生产？  
  routes
})

// 路由拦截的目的是非法用户不能进入指定页面，看不到页面结构和具体内容
// axios拦截的目的是，即使非法用户进入了页面，后台也不返回数据
router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '后台管理系统';
  // 登录验证
  let info = JSON.parse(localStorage.getItem('userInfo')) || {};
  if(info.token) {
    // token存在 表示已经登录
    next();
  }else {
    // 未登录可以访问首页和登录页
    if(to.path === '/' || to.path === '/login') {
      next();
    }else {
      // 其他页面
      next('/login');
    }
  }
})

export default router
